import { _decorator, Component, Node, Vec3, Quat } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('BorrowNode')
export class BorrowNode extends Component {
    @property(Node)
    public borrowNode: Node | null = null;

    @property(Node)
    public originalParent: Node | null = null;

    @property
    defaultAttach = false;

    private attached: boolean = false;

    protected onLoad(): void {
        if (this.borrowNode && this.defaultAttach) {
            this.attachTo(this.borrowNode);
        }
    }

    /**
     * 将当前节点视觉上附着到目标节点，但保持 transform 不变
     * @param target 目标节点（模拟挂载的父节点）
     */
    public attachTo(target: Node) {
        if (this.attached) return;

        this.originalParent = this.node.parent;
        this.borrowNode = target;
        this.attached = true;

        this.node.setParent(this.borrowNode);
        this._attachTarget();

        this.originalParent?.on(
            Node.EventType.TRANSFORM_CHANGED,
            this._attachTarget,
            this,
        );
    }

    /**
     * 恢复原始父节点，并保持 transform 不变
     */
    public detach() {
        if (!this.attached || !this.originalParent) return;

        const worldPos = this.node.worldPosition.clone();
        const worldRot = this.node.worldRotation.clone();
        const worldScale = this.node.worldScale.clone();

        this.node.setParent(this.originalParent);

        this.node.setWorldPosition(worldPos);
        this.node.setWorldRotation(worldRot);
        this.node.setWorldScale(worldScale);

        this.attached = false;
        this.borrowNode = null;

        this.originalParent.off(
            Node.EventType.TRANSFORM_CHANGED,
            this._attachTarget,
            this,
        );
    }

    /**
     * 每帧同步 transform 到目标节点位置，但保持世界 transform（可视一致）
     */
    lateUpdate() {
        // this._attachTarget();
    }

    private _attachTarget() {
        if (!this.attached || !this.originalParent) return;

        const worldPos = this.originalParent.worldPosition.clone();
        const worldRot = this.originalParent.worldRotation.clone();
        const worldScale = this.originalParent.worldScale.clone();

        // 确保视觉状态稳定
        this.node.setWorldPosition(worldPos);
        this.node.setWorldRotation(worldRot);
        this.node.setWorldScale(worldScale);
    }
}
